package com.general.seckill;

import com.alibaba.fastjson.JSON;
import com.general.seckill.Request.RequestEntity;
import com.general.seckill.feign.OrderServiceFeign;
import com.general.seckill.feign.StockServiceFeign;
import com.general.seckill.rocketmq.RocketMQConfig;
import com.general.seckill.rocketmq.SecKillEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: SecondKillController
 * @author: general
 * @version: 1.0
 * @create: 2022-04-30 15:58
 **/
@RestController
@RequestMapping("seckill")
@Slf4j
public class SecondKillController {

    @Resource
    private StockServiceFeign stockServiceFeign;

    @Resource
    private OrderServiceFeign orderServiceFeign;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private RocketMQConfig rocketMQConfig;

    @PostMapping("kill")
    public Map<String, Object> seckill(@RequestBody RequestEntity entity){
        // 异步发送消息
        // Send user-defined object
        SecKillEntity secKillEntity = new SecKillEntity(entity.getUserId(), entity.getProductId());
        rocketMQTemplate.asyncSend(rocketMQConfig.getSecondKillTopic(),
                secKillEntity ,
           new SendCallback() {
            @Override
            public void onSuccess(SendResult var1) {
                System.out.printf("async onSucess SendResult=%s %n", var1);
            }

            @Override
            public void onException(Throwable var1) {
                log.error("异步发送消息失败：params:{}, e"+var1, JSON.toJSONString(secKillEntity));
            }
        });

        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "seckill success");
        return map;
    }
}
